package com.dlyk.service.impl;

import com.alibaba.excel.EasyExcel;
import com.dlyk.constant.Constants;
import com.dlyk.manager.CustomerManager;
import com.dlyk.mapper.CustomerMapper;
import com.dlyk.model.Customer;
import com.dlyk.query.BaseQuery;
import com.dlyk.query.CustomerQuery;
import com.dlyk.result.CustomerExcel;
import com.dlyk.service.CustomerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private CustomerManager customerManager;

    @Resource
    private CustomerMapper customerMapper;

    /**
     * 添加客户（线索转换客户）
     */
    @Override
    public int saveCustomerByClue(CustomerQuery customerQuery) {

        // 调用 通用业务处理层（Manager层）
        return customerManager.saveCustomerByClue(customerQuery);
    }

    /**
     * 获取客户列表（分页查询）
     */
    @Override
    public PageInfo<Customer> getCustomerListByPage(Integer current) {

        // 1、设置PageHelper
        PageHelper.startPage(current, Constants.PAGE_SIZE);

        // 2、查询（传入一个BaseQuery类，用于拼接sql语句）
        List<Customer> customerList = customerMapper.selectCustomerListByPage(BaseQuery.builder().build());

        // 3、封装分页数据到PageInfo
        PageInfo<Customer> customerPageInfo = new PageInfo<>(customerList);

        return customerPageInfo;
    }

    /**
     * 导出客户的信息为Excel
     */
    @Override
    public void exportCustomerListByExcel(HttpServletResponse response, List<String> ids) throws IOException {

        // 要想让浏览器弹出下载框，后端要设置一下响应信息
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        // 设置响应头信息和文件名
        response.setHeader("Content-disposition", "attachment;filename=customer.xlsx");

        // 获取要导出客户信息的集合，调用mapper的时候，如果ids参数为null，就表示导出所有的客户信息Excel，否则表示导出指定客户的信息Excel
        List<CustomerExcel> customerExcelList = customerMapper.selectCustomerListByExcel(ids);

        EasyExcel.write(response.getOutputStream(), CustomerExcel.class)
                .sheet()
                .doWrite(customerExcelList);
    }

    /**
     * 根据id获取客户详情
     */
    @Override
    public Customer getCustomerDetailById(Integer id) {
        return customerMapper.selectCustomerDetailById(id);
    }

    /**
     * 编辑客户详细信息
     */
    @Override
    public int editCustomer(CustomerQuery customerQuery) {
        return customerManager.editCustomer(customerQuery);
    }

}

